﻿using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.Organizations;
using Abp.UI;
using Camc.Quality.Common;
using Camc.Quality.Dto;
using Camc.Quality.IOperationHistory;
using Camc.Quality.OperationHistory;
using Camc.Quality.ProductionPlan;
using Camc.Quality.WorkFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Camc.Quality.ProductionControl
{
    /// <summary>
    /// 生产报工
    /// </summary>
    public class ProductionReportAppService : QualityAppServiceBase
    {
        private readonly IRepository<ProductionScheduler, Guid> _productionSchedulerRepository;
        private readonly IRepository<JobWorker, Guid> _jobWorkerRepository;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;

        private readonly StatisticalExcelAppService _statisticalExcelAppService;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
        public ProductionReportAppService(IRepository<ProductionScheduler, Guid> productionSchedulerRepository,
            IOperationHistoryAppService iOperationHistoryAppService,
            IRepository<JobWorker, Guid> jobWorkerRepository,
            StatisticalExcelAppService statisticalExcelAppService,
            IRepository<OrganizationUnit, long> organizationUnitRepository,
             IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository
            )
        {
            _productionSchedulerRepository = productionSchedulerRepository;
            _jobWorkerRepository = jobWorkerRepository;
            _iOperationHistoryAppService = iOperationHistoryAppService;
            _statisticalExcelAppService = statisticalExcelAppService;
            _organizationUnitRepository = organizationUnitRepository;
            _userOrganizationUnitRepository = userOrganizationUnitRepository;

        }
        /// <summary>
        ///查询报工管理接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedResultDto<ProductionReportOutput> GetTaskReport(ProductionReport input)
        {
            var result = _productionSchedulerRepository.GetAll().Where(d => d.Issue == true)
            .WhereIf(!string.IsNullOrEmpty(input.JobNumber), d => d.JobNumber.Contains(input.JobNumber))
            .WhereIf(!string.IsNullOrEmpty(input.TechniqueName), d => d.TechniqueName.Contains(input.TechniqueName))
            .WhereIf(!string.IsNullOrEmpty(input.ProcessesName), d => d.ProductionName.Contains(input.ProcessesName))
            .WhereIf(!string.IsNullOrEmpty(input.WorkStepName), d => d.WorkStepName.Contains(input.WorkStepName))
            .WhereIf(input.StartTime != null, d => d.StartTime >= input.StartTime.Value)
            .WhereIf(input.EndTime != null, d => d.EndTime <= input.EndTime.Value)
            .WhereIf(!string.IsNullOrEmpty(input.OrganizationUnitDesc), d => d.OrganizationUnitDesc.Contains(input.OrganizationUnitDesc))
            .WhereIf(!string.IsNullOrEmpty(input.UserName), d => d.UserName.Contains(input.UserName))
            .WhereIf(input.ProductingStatus != null, d => d.ProductingStatus == input.ProductingStatus)
            .WhereIf(input.AssemblyStartTime != null, d => d.AssemblyStartTime >= input.AssemblyStartTime.Value)
            .WhereIf(input.AssemblyEndTime != null, d => d.AssemblyEndTime <= input.AssemblyEndTime.Value);
            int count = result.Count();
            result = result.OrderByDescending(d => d.CreationTime).PageBy(input);
            var temp = ObjectMapper.Map<List<ProductionReportOutput>>(result);
            return new PagedResultDto<ProductionReportOutput>(count, temp); 
        }
        /// <summary>
        /// 生产报工记录查询接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedResultDto<ProductionReportOutput> GetTaskReportRecord(ProductionReport input)
        {
            var result = _productionSchedulerRepository.GetAll().Where(d => d.Issue == true&&(d.ProductingStatus==ProductingStatus.已完成|| d.ProductingStatus == ProductingStatus.待返工))
            .WhereIf(!string.IsNullOrEmpty(input.JobNumber), d => d.JobNumber.Contains(input.JobNumber))
            .WhereIf(!string.IsNullOrEmpty(input.TechniqueName), d => d.TechniqueName.Contains(input.TechniqueName))
            .WhereIf(!string.IsNullOrEmpty(input.ProcessesName), d => d.ProductionName.Contains(input.ProcessesName))
            .WhereIf(!string.IsNullOrEmpty(input.WorkStepName), d => d.WorkStepName.Contains(input.WorkStepName))
            .WhereIf(input.StartTime != null, d => d.StartTime >= input.StartTime.Value)
            .WhereIf(input.EndTime != null, d => d.EndTime <= input.EndTime.Value)
            .WhereIf(!string.IsNullOrEmpty(input.OrganizationUnitDesc), d => d.OrganizationUnitDesc.Contains(input.OrganizationUnitDesc))
            .WhereIf(!string.IsNullOrEmpty(input.UserName), d => d.UserName.Contains(input.UserName))
            .WhereIf(input.ProductingStatus != null, d => d.ProductingStatus == input.ProductingStatus)
            .WhereIf(input.AssemblyStartTime != null, d => d.AssemblyStartTime >= input.AssemblyStartTime.Value)
            .WhereIf(input.AssemblyEndTime != null, d => d.AssemblyEndTime <= input.AssemblyEndTime.Value);
            int count = result.Count();
            result = result.OrderByDescending(d => d.CreationTime).PageBy(input);
            var temp = ObjectMapper.Map<List<ProductionReportOutput>>(result);
            return new PagedResultDto<ProductionReportOutput>(count, temp);
        }
        /// <summary>
        /// 开始报工
        /// </summary>
        /// <param name="taskId"></param>
        public ResultMessage StartTaskReport(Guid taskId)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var temp = _productionSchedulerRepository.FirstOrDefault(d => d.Id == taskId);
                if (temp != null)
                {
                    temp.ProductingStatus = ProductingStatus.生产中;
                    _productionSchedulerRepository.Update(temp);
                    _iOperationHistoryAppService.InsertOperationLogNew(taskId, BusinessTypes.生产报工, OperationTypes.开始报工, "开始报工:" + temp.JobNumber + "信息");
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 任务完成
        /// </summary>
        /// <param name="taskId"></param>
        public void FinishTaskReport(Guid taskId)
        {
            var temp = _productionSchedulerRepository.FirstOrDefault(d => d.Id == taskId);
            if (temp != null)
            {
                temp.ProductingStatus = ProductingStatus.已完成;
                _productionSchedulerRepository.Update(temp);
                _iOperationHistoryAppService.InsertOperationLogNew(taskId, BusinessTypes.生产报工, OperationTypes.已完成, "已完成:" + temp.JobNumber + "信息");
            }
        }
        public ResultMessage DefendJobWorker(DefendJobWorkerInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                if (input.IdList.Count == 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "人员列表不可为空!";
                    return resultMessage;
                    //throw new Exception("人员列表不可为空!");
                }
                var proTemp = _productionSchedulerRepository.GetAll().Where(d => input.IdList.Contains(d.Id));
                foreach (var item in proTemp)
                {
                    item.UserId = input.UserId;
                    item.UserName = input.UserName;
                    var jobWorkers = _jobWorkerRepository.GetAll().Where(d => d.TaskId == item.Id).ToList();
                    List<long> userArray = new List<long>();
                    if (input.UserId.Contains(","))
                    {
                        userArray = input.UserId.Split(',').ToList().Select<string, long>(x => Convert.ToInt64(x)).ToList();
                        //var query = from temp in UserManager.Users.Where(d => userArray.Contains(d.Id))
                        //            join ou in _userOrganizationUnitRepository.GetAll() on temp.Id equals ou.UserId
                        //            join cp in _organizationUnitRepository.GetAll() on ou.OrganizationUnitId equals cp.Id
                        //            select new
                        //            {
                        //                UserId = temp.Id,
                        //                Id = cp.Id,
                        //                DisplayName = cp.DisplayName
                        //            };

                        //item.OrganizationUnitId = string.Join(",", query.Select(d => d.Id));
                        //item.OrganizationUnitDesc = string.Join(",", query.Select(d => d.DisplayName));
                    }
                    else
                    {
                        userArray.Add(Convert.ToInt64(input.UserId));
                    }
                    item.OrganizationUnitId = input.OrganizationUnitId;
                    item.OrganizationUnitDesc = input.OrganizationUnitDesc;
                    if (jobWorkers.Count > 0)
                    {
                        var tempArray = jobWorkers.Select(d => d.UserId);
                        List<long> updateArr = new List<long>();
                        List<long> deleteArr = new List<long>();
                        List<long> addArr = new List<long>();
                        //更新
                        updateArr = tempArray.Intersect(userArray).ToList();
                        //删除
                        deleteArr = tempArray.Except(userArray).ToList();
                        //添加
                        addArr = userArray.Except(tempArray).ToList();

                        for (int i = 0; i < updateArr.Count; i++)
                        {
                            var tempJok = jobWorkers.FirstOrDefault(d => d.UserId == updateArr[i]);

                            //var query = (from temp in UserManager.Users.Where(d => d.Id == updateArr[i])
                            //             join ou in _userOrganizationUnitRepository.GetAll() on temp.Id equals ou.UserId
                            //             join cp in _organizationUnitRepository.GetAll() on ou.OrganizationUnitId equals cp.Id
                            //             select new
                            //             {
                            //                 UserId = temp.Id,
                            //                 Id = cp.Id,
                            //                 DisplayName = cp.DisplayName
                            //             }).ToList();
                            //  tempJok.OrganizationUnitId =.Where(d => d.UserId == i).First().OrganizationUnitId;
                            if (!input.OrganizationUnitId.Contains(","))
                            {
                                tempJok.OrganizationUnitId = Convert.ToInt64(input.OrganizationUnitId) ;
                                tempJok.OrganizationUnitDesc = input.OrganizationUnitDesc;
                            }
       
                            _jobWorkerRepository.Update(jobWorkers[i]);
                        }

                        for (int i = 0; i < deleteArr.Count; i++)
                        {
                            var tempJok = jobWorkers.FirstOrDefault(d => d.UserId == deleteArr[i]);
                            _jobWorkerRepository.Delete(jobWorkers[i]);
                        }
                        for (int i = 0; i < addArr.Count; i++)
                        {
                            JobWorker worker = new JobWorker();
                            worker.TaskId = item.Id;
                            worker.UserId = addArr[i];
                            worker.UserName = UserManager.Users.FirstOrDefault(d => d.Id == addArr[i]).Surname + UserManager.Users.FirstOrDefault(d => d.Id == addArr[i]).Name;
                            worker.PerformanceHour = 0;
                            if (!input.OrganizationUnitId.Contains(","))
                            {
                                worker.OrganizationUnitId = Convert.ToInt64(input.OrganizationUnitId);
                                worker.OrganizationUnitDesc = input.OrganizationUnitDesc;

                            }
                            // worker.OrganizationUnitId = _userOrganizationUnitRepository.FirstOrDefault(d => d.UserId == addArr[i]).OrganizationUnitId;
                            //worker.OrganizationUnitDesc = _organizationUnitRepository.GetAll().Where(d => d.Id == worker.OrganizationUnitId).FirstOrDefault().DisplayName;
                            _jobWorkerRepository.Insert(worker);

                        }
                    }
                    _productionSchedulerRepository.Update(item);
                    _iOperationHistoryAppService.InsertOperationLogNew(item.Id, BusinessTypes.生产报工, OperationTypes.维护班组人员, "维护:" + item.JobNumber + "班组信息:" + item.OrganizationUnitDesc + ",班组人员:" + item.UserName);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        /// <summary>
        ///根据Id获取生产报工详细信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public ProductionJobOutput GetTaskById(Guid guid)
        {
            var proTask = _productionSchedulerRepository.Get(guid);
            ProductionJobOutput taskOutput = new ProductionJobOutput();
            taskOutput = ObjectMapper.Map<ProductionJobOutput>(proTask);
            if (!string.IsNullOrEmpty(proTask.UserId))
            {
                var jobWorkers = _jobWorkerRepository.GetAll().Where(d => d.TaskId == guid).ToList();
                if (jobWorkers.Count == 0)
                {
                    List<JobWorker> workers = new List<JobWorker>();
                    List<string> userArray = new List<string>();
                    List<string> userIdArray = new List<string>();
                    List<string> OrganizationUnitIdArray = new List<string>();
                    List<string> OrganizationUnitDescArray = new List<string>();
                    if (proTask.UserName.Contains(","))
                    {
                        userArray = proTask.UserName.Split(',').ToList();
                        userIdArray = proTask.UserId.Split(',').ToList();
                        OrganizationUnitIdArray = proTask.OrganizationUnitId.Split(',').ToList();
                        OrganizationUnitDescArray = proTask.OrganizationUnitDesc.Split(',').ToList();
                    }
                    else
                    {
                        userArray.Add(proTask.UserName);
                        userIdArray.Add(proTask.UserId);
                        OrganizationUnitIdArray.Add(proTask.OrganizationUnitId);
                        OrganizationUnitDescArray.Add(proTask.OrganizationUnitDesc);
                    }
                    for (int i = 0; i < userArray.Count; i++)
                    {
                        JobWorker worker = new JobWorker();
                        worker.TaskId = proTask.Id;
                        worker.UserId = int.Parse(userIdArray[i]);
                        worker.UserName = userArray[i];
                        worker.PerformanceHour = proTask.PerformanceHour;
                        worker.OrganizationUnitId = int.Parse(OrganizationUnitIdArray[i]);
                        worker.OrganizationUnitDesc = OrganizationUnitDescArray[i];
                        _jobWorkerRepository.Insert(worker);
                        workers.Add(worker);
                    }
                    taskOutput.JobWorkers = ObjectMapper.Map<List<JobWorkerOut>>(workers);
                    return taskOutput;
                }
                else
                {
                    taskOutput.JobWorkers = ObjectMapper.Map<List<JobWorkerOut>>(jobWorkers);
                    return taskOutput;
                }
            }
            else
            {
                taskOutput.JobWorkers  =new List<JobWorkerOut>();
                return taskOutput;
            }
        }
        /// <summary>
        /// 生产报工
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage MakeRepot(MakeReportInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var workers = _jobWorkerRepository.GetAll().Where(d => d.TaskId == input.TaskId);
                var tempArray = workers.Select(d => d.Id);
                var inputArray = input.JobWorkers.Select(d => d.Id.Value);
                List<Guid> updateArr = new List<Guid>();
                List<Guid> deleteArr = new List<Guid>();
                List<Guid> addArr = new List<Guid>();
                //更新
                updateArr = tempArray.Intersect(inputArray).ToList();
                //删除
                deleteArr = tempArray.Except(inputArray).ToList();
                //添加
                addArr = inputArray.Except(tempArray).ToList();
                foreach (var item in updateArr)
                {
                    var temp = workers.FirstOrDefault(d => d.Id == item);
                    var job = input.JobWorkers.FirstOrDefault(d => d.Id == item);
                    if (temp != null && job != null && job.IsCheck == true)
                    {
                        temp.Sort = job.Sort;
                        temp.OrganizationUnitId = job.OrganizationUnitId;
                        temp.OrganizationUnitDesc = job.OrganizationUnitDesc;
                        temp.UserId = job.UserId;
                        temp.UserName = job.UserName;
                        temp.PerformanceHour = job.PerformanceHour;
                        temp.ReportHour = job.ReportHour;
                        temp.ReportTime = DateTime.Now;
                        temp.Remark = job.Remark;
                        _jobWorkerRepository.Update(temp);
                        _iOperationHistoryAppService.InsertOperationLogNew(input.TaskId, BusinessTypes.生产报工, OperationTypes.工时报工, "新增班组人员:" + temp.UserName + ",工时报工:" + job.ReportHour);
                    }
                }
                foreach (var item in deleteArr)
                {
                    var jobWork = _jobWorkerRepository.Get(item);
                    _jobWorkerRepository.Delete(jobWork);
                    _iOperationHistoryAppService.InsertOperationLogNew(input.TaskId, BusinessTypes.生产报工, OperationTypes.工时报工, "删除班组人员:" + jobWork.UserName);
                }
                foreach (var item in addArr)
                {
                    JobWorker temp = new JobWorker();
                    var job = input.JobWorkers.FirstOrDefault(d => d.Id == item);
                    if (job != null && job.IsCheck == true)
                    {
                        temp.Sort = job.Sort;
                        temp.OrganizationUnitId = job.OrganizationUnitId;
                        temp.OrganizationUnitDesc = job.OrganizationUnitDesc;
                        temp.UserId = job.UserId;
                        temp.UserName = job.UserName;
                        temp.PerformanceHour = job.PerformanceHour;
                        temp.ReportHour = job.ReportHour;
                        temp.ReportTime = DateTime.Now;
                        temp.Remark = job.Remark;
                        _jobWorkerRepository.Insert(temp);
                        _iOperationHistoryAppService.InsertOperationLogNew(input.TaskId, BusinessTypes.生产报工, OperationTypes.工时报工, temp.UserName + "工时报工:" + job.ReportHour);
                    }
                }
                var task = _productionSchedulerRepository.Get(input.TaskId);
                task.ProductedStatus = ProductedStatus.已提报;
                if (input.operation == 1)
                {
                    task.ProductingStatus = ProductingStatus.已完成;
                }
                else if (input.operation == 2)
                {

                    task.ProductingStatus = ProductingStatus.生产中;
                }
                _productionSchedulerRepository.Update(task);
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 撤销
        /// </summary>
        /// <param name="input"></param>
        public void BackTaskReport(BackInput input)
        {
            var productionScheduler = _productionSchedulerRepository.GetAll().Where(d => d.Id == input.Id).FirstOrDefault();
            if (productionScheduler != null)
            {
                productionScheduler.Remark = input.BackReason;
                productionScheduler.Issue = false;
                productionScheduler.ProductingStatus = ProductingStatus.已撤销;
                _productionSchedulerRepository.Update(productionScheduler);
                _iOperationHistoryAppService.InsertOperationLogNew(input.Id, BusinessTypes.生产报工, OperationTypes.撤销, "撤销:" + productionScheduler.JobNumber);
            }
        }
        /// <summary>
        /// 返工
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage BackTaskReportRework(BackInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var productionScheduler = _productionSchedulerRepository.GetAll().Where(d => d.Id == input.Id).FirstOrDefault();
                if (productionScheduler != null)
                {
                    productionScheduler.Remark = input.BackReason;
                    productionScheduler.ProductingStatus = ProductingStatus.待返工;
                    _productionSchedulerRepository.Update(productionScheduler);
                    _iOperationHistoryAppService.InsertOperationLogNew(input.Id, BusinessTypes.生产报工, OperationTypes.返工, "返工:" + productionScheduler.JobNumber);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 获取所有生产状态
        /// </summary>
        /// <returns></returns>
        public List<WorkLabelOutPut> GetProductingStatusDesc()
        {
            List<WorkLabelOutPut> temp = new List<WorkLabelOutPut>();
            foreach (int myCode in Enum.GetValues(typeof(ProductingStatus)))
            {
                WorkLabelOutPut work = new WorkLabelOutPut();
                string strName = Enum.GetName(typeof(ProductingStatus), myCode);//获取名称
                work.Value = myCode;
                work.Label = strName;
                temp.Add(work);
            }
            return temp;
        }
        /// <summary>
        /// 获取人员
        /// </summary>
        /// <param name="model"></param>
        /// <param name="lotNo"></param>
        /// <returns></returns>
        public List<WorkLabelOutPut> GetProductingPerson(Guid? model,Guid? lotNo)
        {
            List<WorkLabelOutPut> tempPut = new List<WorkLabelOutPut>();
            var query = from temp in _jobWorkerRepository.GetAll()
                        join temp2 in _productionSchedulerRepository.GetAll() on temp.TaskId equals temp2.Id
                        select new 
                        {
                            UserId = temp.UserId,
                            UserName = temp.UserName,
                            Model = temp2.ModelId,
                            LotNo = temp2.LotNoId,
                        };
            var result = query.WhereIf(model != null, d => d.Model == model)
            .WhereIf(lotNo != null, d => d.LotNo == lotNo).ToList();
            if (result.Count > 0)
            {
                foreach (var item in result)
                {
                    WorkLabelOutPut work = new WorkLabelOutPut();
                    work.Label = item.UserName;
                    work.Value = Convert.ToInt32(item.UserId);
                    tempPut.Add(work);
                }
            }
            return tempPut.Distinct().ToList();
        }
        #region 工时管理
        /// <summary>
        /// 人员工时统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedResultDto<ManHourOutput> GetStatisticalManHour(ManHourInput input)
        {
            var query = from temp in _jobWorkerRepository.GetAll()
                        join temp2 in _productionSchedulerRepository.GetAll() on temp.TaskId equals temp2.Id
                        where temp2.ProductedStatus== ProductedStatus.已提报 && temp2.ProductingStatus == ProductingStatus.已完成
                        select new ManHourOutput
                        {
                            UserId = temp.UserId,
                            UserName = temp.UserName,
                            JobNumber = temp2.JobNumber,
                            Model = temp2.Model,
                            LotNo = temp2.LotNo,
                            ModelId= temp2.ModelId,
                            LotNoId=temp2.LotNoId,
                            TechniqueNumber = temp2.TechniqueNumber,
                            TechniqueName = temp2.TechniqueName,
                            DrawingNo = temp2.DrawingNo,
                            ProductionName = temp2.ProductionName,
                            WorkStepDrawingNo = temp2.WorkStepDrawingNo,
                            WorkStepName = temp2.WorkStepName,
                            WorkingHour = temp2.WorkingHour,
                            ReportHour = temp.ReportHour,
                            ReportTime = temp.ReportTime
                        };
            var result = query.WhereIf(input.ModelId!=null, d => d.ModelId==input.ModelId)
            .WhereIf(input.LotNoId!=null, d => d.LotNoId==input.LotNoId)
            .WhereIf(input.UserIdList != null, d => input.UserIdList.Contains(d.UserId))
            .WhereIf(input.StartTime != null, d => d.ReportTime >= input.StartTime.Value)
            .WhereIf(input.EndTime != null, d => d.ReportTime <= input.EndTime.Value);
            int count = result.Count();
            var tempResult = result.OrderByDescending(d => d.ReportTime).PageBy(input);
            return new PagedResultDto<ManHourOutput>(count, tempResult.ToList());
        }
        /// <summary>
        /// 班组工时统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<ManGroupOutput> GetStatisticalGroupHour(ManHourInput input)
        {

            var tempQuery = from temp in _jobWorkerRepository.GetAll()
                            join temp2 in _productionSchedulerRepository.GetAll() on temp.TaskId equals temp2.Id
                            where temp2.ProductedStatus == ProductedStatus.已提报 && temp2.ProductingStatus == ProductingStatus.已完成
                            select new
                            {
                                UserId = temp.UserId,
                                UserName = temp.UserName,
                                Model = temp2.Model,
                                LotNo = temp2.LotNo,
                                ModelId = temp2.ModelId,
                                LotNoId = temp2.LotNoId,
                                WorkingHour = temp2.WorkingHour,
                                ReportHour = temp.ReportHour,
                                ReportTime = temp.ReportTime,
                                OrganizationUnitId = temp.OrganizationUnitId,
                                OrganizationUnitDesc = temp.OrganizationUnitDesc,
                                TaskId = temp.TaskId,
                            };
            var tempResult = tempQuery.WhereIf(input.ModelId != null, d => d.ModelId == input.ModelId)
                        .WhereIf(input.LotNoId != null, d => d.LotNoId == input.LotNoId)
                        .WhereIf(input.OrganizationUnitIdList != null, d => input.OrganizationUnitIdList.Contains(d.OrganizationUnitId))
                        .WhereIf(input.StartTime != null, d => d.ReportTime >= input.StartTime.Value)
                        .WhereIf(input.EndTime != null, d => d.ReportTime <= input.EndTime.Value)
                        .OrderByDescending(d => d.ReportTime);

            var tempReturn = from query in tempResult
                             group query by new { query.OrganizationUnitId, query.OrganizationUnitDesc, query.UserId, query.UserName, query.Model, query.LotNo } into g
                             select new ManGroupOutput
                             {
                                 OrganizationUnitId = g.Key.OrganizationUnitId,
                                 OrganizationUnitDesc = g.Key.OrganizationUnitDesc,
                                 UserId = g.Key.UserId,
                                 UserName = g.Key.UserName,
                                 Model = g.Key.Model,
                                 LotNo= g.Key.LotNo,
                                 TaskConut = g.Select(d=>d.TaskId).Distinct().Count(),
                                 SumWorkingHour = g.Sum(d => d.WorkingHour),
                                 SumReportHour = g.Sum(d => d.ReportHour),
                             };
            return tempReturn.ToList();
        }
        /// <summary>
        /// 人员工时导出Excel
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string ExportPeopleHour(ManHourInput input)
        {
            var query = from temp in _jobWorkerRepository.GetAll()
                        join temp2 in _productionSchedulerRepository.GetAll() on temp.TaskId equals temp2.Id
                        select new ManHourOutput
                        {
                            UserId = temp.UserId,
                            UserName = temp.UserName,
                            JobNumber = temp2.JobNumber,
                            Model = temp2.Model,
                            LotNo = temp2.LotNo,
                            ModelId = temp2.ModelId,
                            LotNoId = temp2.LotNoId,
                            TechniqueNumber = temp2.TechniqueNumber,
                            TechniqueName = temp2.TechniqueName,
                            DrawingNo = temp2.DrawingNo,
                            ProductionName = temp2.ProductionName,
                            WorkStepDrawingNo = temp2.WorkStepDrawingNo,
                            WorkStepName = temp2.WorkStepName,
                            WorkingHour = temp2.WorkingHour,
                            ReportHour = temp.ReportHour,
                            ReportTime = temp.ReportTime
                        };
            var result = query.WhereIf(input.ModelId != null, d => d.ModelId == input.ModelId)
            .WhereIf(input.LotNoId != null, d => d.LotNoId == input.LotNoId)
            .WhereIf(input.UserIdList != null, d => input.UserIdList.Contains(d.UserId))
            .WhereIf(input.StartTime != null, d => d.ReportTime >= input.StartTime.Value)
            .WhereIf(input.EndTime != null, d => d.ReportTime <= input.EndTime.Value);
            return _statisticalExcelAppService.ExportStatisticalOwnHour(result.ToList());
        }
        /// <summary>
        /// 导出班组工时
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string ExportGroupHour(ManHourInput input)
        {
            var tempQuery = from temp in _jobWorkerRepository.GetAll()
                            join temp2 in _productionSchedulerRepository.GetAll() on temp.TaskId equals temp2.Id
                            select new
                            {
                                UserId = temp.UserId,
                                UserName = temp.UserName,
                                Model = temp2.Model,
                                LotNo = temp2.LotNo,
                                ModelId = temp2.ModelId,
                                LotNoId = temp2.LotNoId,
                                WorkingHour = temp2.WorkingHour,
                                ReportHour = temp.ReportHour,
                                ReportTime = temp.ReportTime,
                                OrganizationUnitId = temp.OrganizationUnitId,
                                OrganizationUnitDesc = temp.OrganizationUnitDesc,
                                TaskId = temp.TaskId,
                            };
            var tempResult = tempQuery.WhereIf(input.ModelId != null, d => d.ModelId == input.ModelId)
                        .WhereIf(input.LotNoId != null, d => d.LotNoId == input.LotNoId)
                        .WhereIf(input.OrganizationUnitIdList != null, d => input.OrganizationUnitIdList.Contains(d.OrganizationUnitId))
                        .WhereIf(input.StartTime != null, d => d.ReportTime >= input.StartTime.Value)
                        .WhereIf(input.EndTime != null, d => d.ReportTime <= input.EndTime.Value);

            var tempReturn = from query in tempResult
                             group query by new { query.OrganizationUnitId, query.OrganizationUnitDesc, query.UserId, query.UserName, query.Model, query.LotNo } into g
                             select new ManGroupOutput
                             {
                                 OrganizationUnitId = g.Key.OrganizationUnitId,
                                 OrganizationUnitDesc = g.Key.OrganizationUnitDesc,
                                 UserId = g.Key.UserId,
                                 UserName = g.Key.UserName,
                                 Model = g.Key.Model,
                                 LotNo = g.Key.LotNo,
                                 TaskConut = g.Select(d => d.TaskId).Distinct().Count(),
                                 SumWorkingHour = g.Sum(d => d.WorkingHour),
                                 SumReportHour = g.Sum(d => d.ReportHour),
                             };
            return _statisticalExcelAppService.ExportStatisticalGroupHour(tempReturn.ToList());
        }
        #endregion
    }
}
